<?php
namespace core;

/**
 * 事件处理相关操作
 */
class Event
{
  static private $EventList=array();

  // 格式化回调函数
  static function callback($callback){
    $cb=false;
    if (is_callable($callback)){
      $cb=$callback;
    }elseif (is_array($callback)){
      // $cb=create_function("\$data","return $callback(\$data);");
      $cb=function($data) use ($callback) {
        return call_user_func_array($callback,array($data));
      };
    }elseif (is_string($callback)){
      // $cb=create_function("\$data","return $callback(\$data);");
      $cb=function($data) use ($callback) {
        return $callback($data);
      };
    }
    if (!is_callable($cb)){
      throw new Exception("Event callback error: ".print_r($callback,true));
    }
    return $cb;
  }
  static function on($event,$callback,$begin=false){
    $event=strtolower($event);
    $cb=self::callback($callback);

    if (!isset(self::$EventList[$event])) self::$EventList[$event]=array();

    if ($begin){
      array_unshift(self::$EventList[$event],$cb);
    }else{
      array_push(self::$EventList[$event],$cb);
    }

  }
  static function clear($event=""){
    if (empty($event)){
      self::$EventList=array();
    }else{
      self::$EventList[$event]=array();
    }
  }
  static function trigger($event,$data=""){
    $event=strtolower($event);
    if (isset(self::$EventList[$event])){
      foreach (self::$EventList[$event] as $cb) {
        $data=$cb($data);
      }
    }
    return $data;
  }

}
?>
